package com.css.apps.base.user.action.relate;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.css.apps.base.common.provider.UserQueryProvider;
import com.css.apps.base.user.action.UserAction;
import com.css.apps.base.user.model.UserRelateGroup;
import com.css.core.configuration.Environment;
import com.css.db.query.TransactionCache;
import com.css.util.Ajax;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.opensymphony.xwork.Action;

@SuppressWarnings("serial")
public class AddUserRelateGroup extends UserAction {

	private static Log log = LogFactory.getLog(AddUserRelateGroup.class);
	private String name;

	@Override
	protected String userGo() {
		TransactionCache tx = null;
		try {
			if (StringHelper.isEmpty(name)) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}

			UserRelateGroup item = new UserRelateGroup();
			item.setUserId(UserQueryProvider.currentUser().getUserId());
			item.setName(name);
			tx = new TransactionCache();
			tx.save(item);
			tx.commit();

			JSONObject o = new JSONObject();
			o.put("id", item.getUuid());
			o.put("name", item.getName());
			o.put("count", 0);
			o.put("isParent", true);
			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"), o);
			return Action.SUCCESS;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			if (tx != null) {
				tx.rollback();
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			return Action.ERROR;
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
